var query = require('../../common').Query;
var map = require('../../common').Mapping;
var cache = require('../../common').RefreshCache;

exports.managerTeamPage = function (req, res) {
    query(map.sql.findAllTeamAndMember, req, {}, function (rows) {
        var cursor = 0;
        var obj = map.generateNavBar(req);
        query(map.sql.findAllTeams, req, {}, function (team) {
            rows.forEach(function (e) {
                (function findUntil() {
                    if (team[cursor].t_name == e.t_name) {
                        !team[cursor].member && (team[cursor].member = []);
                        team[cursor].member.push({
                            u_id: e.u_id,
                            u_name: e.u_name,
                            username: e.username,
                            email: e.email,
                            role: e.role
                        })
                    } else {
                        cursor++;
                        findUntil();
                    }
                })();
                if (team[cursor].member) {
                    team[cursor].member.sort(function (a, b) {
                        return a.role == 'manager' ? -1 : 1;
                    });
                }
            });
            obj.team = team;
            res.render('findTeamTpl', obj);
        });
    });
};

exports.updateTeam = function (req, res) {
    query(map.sql.updateTeam, res, req.body, function (rows) {
        if (rows.affectedRows == 1) {
            res.send('success');
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.updateTeamWithLeader = function (req, res) {
    // 1.set old leader role = member.team=null,
    // 2.set new leader role = manager, manager=null,team=target team
    // 3.update all member of team set manager old->new
    var fireOldLeader = "UPDATE user SET role='member',team=NULL WHERE u_id=#old_leader;";
    var setNewLeader = "UPDATE user SET role='manager',team=#t_name,manager=NULL WHERE u_id=#leader;";
    var moveWholeTeamMembers = "UPDATE user SET manager=#leader WHERE team=#t_name";
    query(map.sql.findTeam, res, req.body, function (targetTeam) {
        if (targetTeam && targetTeam.length == 1) {
            if (targetTeam[0].leader) {
                req.body.old_leader = targetTeam[0].leader;
                query(fireOldLeader, res, req.body, function () {
                    query(moveWholeTeamMembers, res, req.body, function () {
                        query(setNewLeader, res, req.body, function () {
                            query(map.sql.updateTeam, res, req.body, function (rows) {
                                if (rows.affectedRows == 1) {
                                    cache();
                                    res.send('success');
                                } else {
                                    res.send({error: 503, description: map.error[503]});
                                }
                            });
                        });
                    });
                });
            } else {
                query(map.sql.updateTeam, res, req.body, function (rows) {
                    query(moveWholeTeamMembers, res, req.body, function () {
                        query(setNewLeader, res, req.body, function () {
                            if (rows.affectedRows == 1) {
                                cache();
                                res.send('success');
                            } else {
                                res.send({error: 503, description: map.error[503]});
                            }
                        });
                    });
                });
            }
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.addNewTeam = function (req, res) {
    query(map.sql.addTeam, res, req.body, function () {
        res.send("success");
    });
};

exports.addTeamMember = function (req, res) {
    req.body.t_name = req.body.team;
    query(map.sql.findTeam, res, req.body, function (team) {
        if (team.length == 1) {
            if (team[0].leader) {
                req.body.leader = team[0].leader;
            }
            query(map.sql.updateMember, res, req.body, function () {
                cache();
                res.send("success");
            });
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.deleteTeam = function (req, res) {
    query("UPDATE team SET status = 'inactive' WHERE t_name = #t_name", res, req.body, function () {
        query("UPDATE user SET role='member' WHERE role='manager' AND team=#t_name", res, req.body, function () {
            query("UPDATE user SET manager=NULL,team=NULL WHERE team = #t_name", res, req.body, function () {
                cache();
                res.send("success");
            });
        });
    })
};